﻿using System;
using System.Device.Location;
using System.Globalization;
using Microsoft.Phone.Reactive;

namespace AuchanScan
{
    public class GeoWatcher
    {
        private NumberFormatInfo nfi = new NumberFormatInfo {NumberDecimalSeparator = "."};
        public GeoCoordinateWatcher Watcher { get; set; }

        public void LaunchGPS()
        {
            Watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default) {MovementThreshold = 30};

            IObservable<IEvent<GeoPositionChangedEventArgs<GeoCoordinate>>> positionEventAsObservable =
                Observable.FromEvent<GeoPositionChangedEventArgs<GeoCoordinate>>(Watcher, "PositionChanged");

            //SAMPLE
            // Take the Observable sequence of all PositionChanged events and use the Sample
            // method to return only one event per second.
            IObservable<IEvent<GeoPositionChangedEventArgs<GeoCoordinate>>> sampledPositionEvents =
                positionEventAsObservable.Sample(TimeSpan.FromMilliseconds(3000));

            // Subscribe to the sampled Observable instead of the original Observable.
            IDisposable sampledPositionSubscription = sampledPositionEvents.Subscribe(
                args => { if (args != null) Watcher_PositionChanged(args.Sender, args.EventArgs); });
            Watcher.Start();
        }


        public event EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>> CoordinateChanged;

        private void Watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            if (CoordinateChanged != null)
            {
                CoordinateChanged(this, e);

                if (e.Position.Location != null)
                {
                    Watcher.Stop();
                }
            }
        }
    }
}